package com.gyg.程序员面试金典;
/**
 * Your TripleInOne object will be instantiated and called as such:
 * TripleInOne obj = new TripleInOne(stackSize);
 * obj.push(stackNum,value);
 * int param_2 = obj.pop(stackNum);
 * int param_3 = obj.peek(stackNum);
 * boolean param_4 = obj.isEmpty(stackNum);
 */

/**
 * 面试题 03.01. 三合一
 * 解题思路：
 * 将数组分成三份，每一份表示一个栈；使用三个index；在每次push，pop的时候，都改变index的值。从下标0开始存储数组。
 * 第一个栈index1 in [0,stackSize)
 * 第二个栈index2 in [stackSize,stackSize2)
 * 第三个栈index3 in [stackSize2,stackSize*3)
 */
public class T03_01 {

    public int[] a;
    private int stackSize;
    private int index1, index2, index3;

    public T03_01(int stackSize) {
        this.stackSize = stackSize;
        a = new int[stackSize * 3];
        index1 = -1;// [0,stackSize)
        index2 = stackSize - 1;//[stackSize,stackSize*2)
        index3 = stackSize * 2 - 1;//[stackSize*2,stackSize*3)
        for (int i = 0; i < a.length; i++) {
            a[i] = -1;
        }
    }

    public void push(int stackNum, int value) {
        if (stackNum == 0) {
            if (index1 + 1 < stackSize) {
                index1++;
                a[index1] = value;
            } else {
                return;
            }
        }
        if (stackNum == 1) {
            if (index2 + 1 < stackSize * 2) {
                index2++;
                a[index2] = value;
            } else {
                return;
            }
        }
        if (stackNum == 2) {
            if (index3 + 1 < stackSize * 3) {
                index3++;
                a[index3] = value;
            }
        }
    }


    public int pop(int stackNum) {
        if (stackNum == 0 && index1 >= 0) {
            index1--;
            return a[index1 + 1];
        }
        if (stackNum == 1 && index2 >= stackSize) {
            index2--;
            return a[index2 + 1];
        }
        if (stackNum == 2 && index3 >= stackSize * 2) {
            index3--;
            return a[index3 + 1];
        }
        return -1;
    }

    public int peek(int stackNum) {
        int result = -1;
        if (stackNum == 0 && index1 >= 0) {
            result = a[index1];
        }
        if (stackNum == 1 && index2 >= stackSize) {
            result = a[index2];
        }
        if (stackNum == 2 && index3 >= stackSize * 2) {
            result = a[index3];
        }
        return result;
    }

    public boolean isEmpty(int stackNum) {
        if (stackNum == 0 && index1 == -1) {
            return true;
        }
        if (stackNum == 1 && index2 == stackSize - 1) {
            return true;
        }
        if (stackNum == 2 && index3 == stackSize * 2 - 1) {
            return true;
        }
        return false;
    }


}
